package com.chen.springsecurity.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.springsecurity.domain.LoginUser;

import com.chen.springsecurity.domain.User;
import com.chen.springsecurity.mapper.MenuMapper;
import com.chen.springsecurity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName UserServiceImpl.java
 * @Description TODO
 * @createTime 2023年08月28日 15:41:00
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户信息
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据用户名查询
        userLambdaQueryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        //如果没有查询到用户就抛出一个异常
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }

        //TODO 查询对应的权限信息
//        List<String> list = new ArrayList<>(Arrays.asList("test","admin"));
        List<String> list= menuMapper.selectPermsByUserId(user.getId());

        //封装的UserDetails对象返回
        return new LoginUser(user,list);
    }
}
